package com.shape.sdk.net;

import android.net.Uri;
import android.os.AsyncTask;

import com.shape.sdk.base.IOUtils;
import com.wandoujia.gson.Gson;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * Created by ouzhiyin on 30/01/2018.
 * 尽量减少依赖，直接用 httpconnection 来实现 http 通信
 */

public class ShapeHttpClient<T extends BaseResponse> {

  public interface Listener<V extends BaseResponse> {
    void onSuccess(V response);
    void onError(int errorCode, String msg);
  }

  private final Class<T> clazz;

  public ShapeHttpClient(Class<T> clazz) {
    this.clazz = clazz;
  }

  public T requestGet(final String path, final Map<String, String> param) {
    T response;
    try {
      Gson gson = new Gson();
      Uri.Builder builder = new Uri.Builder();
      builder.scheme(ShapeContants.BASE_SCHEME)
          .authority(ShapeContants.BASE_HOST)
          .path(path);
      for (Map.Entry<String, String> entry : param.entrySet()) {
        builder.appendQueryParameter(entry.getKey(), entry.getValue());
      }
      URL parsedUrl = new URL(builder.build().toString());
      HttpURLConnection connection = (HttpURLConnection) parsedUrl.openConnection();
      connection.setRequestMethod("GET");
      String body = IOUtils.readString(connection.getInputStream(), "utf-8");
      response = gson.fromJson(body, clazz);
    } catch (Throwable throwable) {
      throwable.printStackTrace();
      return null;
    }
    return response;
  }

  public AsyncTask requestGetAsync(final String path,
                                   final Map<String, String> param,
                                   final Listener<T> listener) {
    AsyncTask<Void, Void, T> task = new AsyncTask<Void, Void, T>() {

      @Override
      protected T doInBackground(Void... params) {
        return requestGet(path, param);
      }

      @Override
      protected void onPostExecute(final T result) {
        if (result == null) {
          listener.onError(-1, "");
        } else {
          if (result.getErrorCode() != 0) {
            listener.onError(result.getErrorCode(), result.getMsg());
          } else {
            listener.onSuccess(result);
          }
        }
      }
    };
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    return task;
  }

  public T requestPost(final String path, final String content) {
    T response;
    OutputStream out = null;
    try {
      Gson gson = new Gson();
      Uri.Builder builder = new Uri.Builder();
      builder.scheme(ShapeContants.BASE_SCHEME)
          .authority(ShapeContants.BASE_HOST)
          .path(path);
      URL parsedUrl = new URL(builder.build().toString());
      HttpURLConnection connection = (HttpURLConnection) parsedUrl.openConnection();
      connection.setRequestMethod("POST");
      connection.setDoOutput(true);
      out = connection.getOutputStream();
      out.write(content.getBytes());
      out.flush();
      out.close();
      String body = IOUtils.readString(connection.getInputStream(), "utf-8");
      response = gson.fromJson(body, clazz);
    } catch (Throwable throwable) {
      throwable.printStackTrace();
      return null;
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

    }
    return response;
  }
}
